package com.glsc.ngateway.opmanage.service.other;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.api.common.ex.GatewayException;
import com.glsc.ngateway.opmanage.aspect.UserCache;
import com.glsc.ngateway.opmanage.utils.RequestTool;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TradeSeatHistory;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domainmapper.TradeSeatHistoryMapper;
import com.glsc.ngateway.common.api.platform.dto.other.TradeSeatHistoryDto;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.TradeSeatHistoryRepository;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author libj
 * @date 2022/4/19
 * 交易单元租用流水实体服务
 */
@Service
public class TradeSeatHistoryService {

    private static final Logger logger = LoggerFactory.getLogger(TradeSeatHistoryService.class);

    @Resource
    private TradeSeatHistoryRepository tradeSeatHistoryRepository;
    @Autowired
    private UserCache userCache;

    @Autowired
    private RequestTool requestTool;

    /**
     * 创建交易单元租用流水信息
     * @param tradeSeatHistoryDto
     */
    public TradeSeatHistoryDto save(TradeSeatHistoryDto tradeSeatHistoryDto) {
        logger.info("创建交易单元租用流水信息，入参tradeSeatHistoryDto：" + tradeSeatHistoryDto);
        //校验数据
        if (null == tradeSeatHistoryDto) {
            throw GatewayException.error("创建信息无效：" + tradeSeatHistoryDto);
        }
        TradeSeatHistory tradeSeatHistory = getTradeSeatHistoryByCodeAndMarket(tradeSeatHistoryDto.getTradeSeatCode(),tradeSeatHistoryDto.getTradeSeatMarket());
//        if (null != tradeSeatHistory) {//流水允许录入多次
//            throw GatewayException.error("创建信息无效，交易单元租用流水信息数据库已经存在，TradeSeatCode：" + tradeSeatHistoryDto.getTradeSeatCode() + ",TradeSeatMarket" + tradeSeatHistoryDto.getTradeSeatMarket());
//        }
        tradeSeatHistory = TradeSeatHistoryMapper.INSTANCE.dto2domain(tradeSeatHistoryDto);
        User createUser = userCache.get(requestTool.getAccountFromRequest());
        tradeSeatHistory.setCreateOperator(createUser.getUsername());
        tradeSeatHistory.setCreateOperatorName(createUser.getName());
        tradeSeatHistory.setState(DictConstant.TRADE_SEAT_STATE_BEGIN);
        tradeSeatHistory.setDataSource(DictConstant.TRADE_SEAT_SOURCE_MANU);
//        RequestTool.fillOpInfo(tradeSeatHistory, DictConstant.OP_SOURCE_WEB, DictConstant.OP_ACTION_ADD);
        TradeSeatHistory tradeSeatHistorySaved = tradeSeatHistoryRepository.save(tradeSeatHistory);

        return TradeSeatHistoryMapper.INSTANCE.domain2dto(tradeSeatHistorySaved);
    }

    /**
     * 批量创建交易单元信息
     */
    public void saveTradeSeatHistoryList(List<TradeSeatHistory> tradeSeatHistoryList) {
        if (CollectionUtil.isEmpty(tradeSeatHistoryList)) {
            return;
        }
//        User createUser=CacheManager.getUserFromRedis(Constant.USER_ADMIN);
        tradeSeatHistoryList.forEach(tradeSeatHistory->{
            tradeSeatHistory.setCreateOperator("admin");
            tradeSeatHistory.setCreateOperatorName("管理员");
            tradeSeatHistory.setOpSource(DictConstant.OP_SOURCE_WEB);
            tradeSeatHistory.setOpAction(DictConstant.OP_ACTION_ADD);
            tradeSeatHistory.setOpOperator(Constant.USER_ADMIN);
            tradeSeatHistory.setOpOperatorName(Constant.USER_ADMIN_NAME);
        });
        //20230928肖丹说etf、lof里没有交易单元和交易账号的不如台账
        tradeSeatHistoryList.removeIf(e -> e.getChangeTypeCode() != null && e.getChangeTypeCode() == 1 && (StrUtil.isEmpty(e.getTradeSeatCode()) || StrUtil.isEmpty(e.getTradeSeatMarket()) ));
        tradeSeatHistoryRepository.saveAll(tradeSeatHistoryList);
    }

    /**
     * 更新交易单元租用流水信息
     * @param tradeSeatHistoryDto
     */
    public TradeSeatHistoryDto update(TradeSeatHistoryDto tradeSeatHistoryDto) {
        logger.info("更新交易单元租用流水信息，入参tradeSeatHistoryDto：" + tradeSeatHistoryDto);
        //校验数据
        if (null == tradeSeatHistoryDto || tradeSeatHistoryDto.getTradeSeatId() == null || tradeSeatHistoryDto.getTradeSeatId() <= 0) {
            throw GatewayException.error("更新信息无效：" + tradeSeatHistoryDto);
        }
        //获取数据库中城市信息
        TradeSeatHistory tradeSeatHistoryDB = getTradeSeatHistoryByTradeSeatId(tradeSeatHistoryDto.getTradeSeatId());
        if(tradeSeatHistoryDB == null){
            throw GatewayException.error("TradeSeatId：" + tradeSeatHistoryDto.getTradeSeatId() + "对应交易单元租用流水信息不存在不允许更新");
        }
        TradeSeatHistory tradeSeatHistory = TradeSeatHistoryMapper.INSTANCE.dto2domain(tradeSeatHistoryDto);
        tradeSeatHistory.setCreateOperator(tradeSeatHistoryDB.getCreateOperator());
        tradeSeatHistory.setCreateOperatorName(tradeSeatHistoryDB.getCreateOperatorName());
//        RequestTool.fillOpInfo(tradeSeatHistory, DictConstant.OP_SOURCE_WEB, DictConstant.OP_ACTION_UPDATE);
        TradeSeatHistory tradeSeatHistorySaved = tradeSeatHistoryRepository.save(tradeSeatHistory);

        return TradeSeatHistoryMapper.INSTANCE.domain2dto(tradeSeatHistorySaved);
    }

    /**
     * 根据TradeSeatId设置为停用标记
     *
     * @return
     */
    @Transactional
    public TradeSeatHistoryDto updateStateEndByTradeSeatId(Integer tradeSeatId) {
        logger.info("停用交易单元租用流水信息，入参tradeSeatId：" + tradeSeatId);
        if (tradeSeatId == null || tradeSeatId <= 0) {
            throw GatewayException.error("TradeSeatId:" + tradeSeatId + "，不合法");
        }

        TradeSeatHistory tradeSeatHistoryDB = getTradeSeatHistoryByTradeSeatId(tradeSeatId);

        if(tradeSeatHistoryDB == null){
            throw GatewayException.error("TradeSeatId：" + tradeSeatId + "对应交易单元租用流水信息不存在不允许删除");
        }

        if (null != tradeSeatHistoryDB && DictConstant.TRADE_SEAT_STATE_BEGIN.equals(tradeSeatHistoryDB.getState())) {
            //设置停用状态
            tradeSeatHistoryDB.setState(DictConstant.TRADE_SEAT_STATE_END);
//            RequestTool.fillOpInfo(tradeSeatHistoryDB, DictConstant.OP_SOURCE_WEB, DictConstant.OP_ACTION_DELETE);

            TradeSeatHistory tradeSeatHistorySaved  = tradeSeatHistoryRepository.save(tradeSeatHistoryDB);
            return TradeSeatHistoryMapper.INSTANCE.domain2dto(tradeSeatHistorySaved);
        }else{
            return null;
        }
    }

    /**
     * 分页条件查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Page<TradeSeatHistoryDto> findPage(String tradeSeatCode,String tradeSeatMarket,String applyDeptName,String useType,String useCompanyName,int pageNo, int pageSize) {
        logger.info("分页条件查询交易单元租用流水信息");
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "tradeSeatId";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);

        Map<String, Object> param=new HashMap<>();
        if(StrUtil.isNotEmpty(tradeSeatCode)){
            param.put("LIKE_tradeSeatCode",tradeSeatCode);
        }
        if(StrUtil.isNotEmpty(tradeSeatMarket)){
            param.put("EQ_tradeSeatMarket",tradeSeatMarket);
        }
        if (StrUtil.isNotEmpty(applyDeptName)) {
            param.put("LIKE_applyDeptName", applyDeptName);
        }
        if (StrUtil.isNotEmpty(useType)) {
            param.put("EQ_useType", useType);
        }
        if(StrUtil.isNotEmpty(useCompanyName)){
            param.put("LIKE_useCompanyName", useCompanyName);
        }

        Page<TradeSeatHistory> ret = tradeSeatHistoryRepository.findAll(SpecificationUtil.buildSpecification(param, TradeSeatHistory.class), pageable);
        return domainToDto(ret,pageable);
    }

    /**
     * 查询交易单元汇总List
     */
    public Page<TradeSeatHistoryDto> findTradeSeatHistorySumPage(String tradeSeatCode,String tradeSeatMarket,Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(PageUtil.initPageNo(pageNo) - 1, PageUtil.initPageSize(pageSize));
        Page<TradeSeatHistory> ret = tradeSeatHistoryRepository.findTradeSeatHistorySumPage(tradeSeatCode,tradeSeatMarket,pageable);
        return domainToDto(ret,pageable);
    }

    /**
     * domain转Dto
     * @param ret
     * @param pageable
     * @return
     */
    private Page<TradeSeatHistoryDto> domainToDto(Page<TradeSeatHistory> ret,Pageable pageable){
        Page<TradeSeatHistoryDto> page;
        //domain转成dto
        if (null != ret && ret.getNumberOfElements() > 0) {
            List<TradeSeatHistoryDto> contentList = TradeSeatHistoryMapper.INSTANCE.domain2dto(ret.getContent());
            page = new PageImpl(contentList, pageable, ret.getTotalElements());
        } else {
            page = new PageImpl(new ArrayList(), pageable, ret.getTotalElements());
        }
        return page;
    }

    /**
     * 根据条件查询List
     */
    public List<TradeSeatHistory> findList(Map<String, Object> param) {
        return tradeSeatHistoryRepository.findAll(SpecificationUtil.buildSpecification(param, TradeSeatHistory.class));
    }

    private TradeSeatHistory getTradeSeatHistoryByTradeSeatId(Integer tradeSeatId){
        return  tradeSeatHistoryRepository.findByTradeSeatId(tradeSeatId) ;
    }

    private TradeSeatHistory getTradeSeatHistoryByCodeAndMarket(String tradeSeatCode, String tradeSeatMarket){
        return  tradeSeatHistoryRepository.findByTradeSeatCodeAndTradeSeatMarket(tradeSeatCode,tradeSeatMarket);
    }
}
